package Petgoods;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/*
卖家控制器，可以上架商品数量（对商品表product进行修改，增加对应商品数量）
 */
public class Sellcontrols {
    public void Shelf() {
        Sellermeau seller = new Sellermeau();
        seller.meau();

        JdbcUtil util = new JdbcUtil();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入想要增加商品名字：");
        String name = sc.nextLine();
        System.out.println("增加的数量");
        int num = sc.nextInt();
        System.out.println("请输入商品价格：");
        int price = sc.nextInt();

        Connection conn = null;
        try {
            conn = util.getConn();
            // 检查商品是否已经存在
            String checkSql = "SELECT id FROM product WHERE name = ?";
            PreparedStatement checkPs = conn.prepareStatement(checkSql);
            checkPs.setString(1, name);
            ResultSet rs = checkPs.executeQuery();

            if (rs.next()) {
                // 商品已存在，增加数量
                String updateSql = "UPDATE product SET number = number + ? WHERE name = ?";
                PreparedStatement updatePs = conn.prepareStatement(updateSql);
                updatePs.setInt(1, num);
                updatePs.setString(2, name);
                int rows = updatePs.executeUpdate();
                if (rows > 0) {
                    System.out.println("上架成功");
                }
            } else {
                // 商品不存在，插入新记录
                String insertSql = "INSERT INTO product (name, number, price) VALUES (?,?,?)";
                PreparedStatement insertPs = conn.prepareStatement(insertSql);
                insertPs.setString(1, name);
                insertPs.setInt(2, num);
                insertPs.setInt(3, price);
                int rows = insertPs.executeUpdate();
                if (rows > 0) {
                    System.out.println("新商品上架成功");
                }
            }
            util.closeResource(rs, conn, null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}